import axios from "axios";
import store from "../store";

const request = axios.create({
	baseURL: "/api",
	timeout: 20000,
});

// 用于请求取消
const CancelToken = axios.CancelToken;

request.interceptors.request.use((config) => {
	let cb;
	// 通过cancelToken构造函数可以创造出实例对象，作为当前请求的唯一标识
	// 回调函数接收一个函数
	config.cancelToken = new CancelToken((callBack) => {
		// 该函数用于取消当前请求
		cb = callBack;
	});
	store.commit("ADDCANCELFN", { url: config.url, cb });

	return config;
});

request.interceptors.response.use((response) => {
	store.commit("DELETECANCELFN", response.config.url);
	return response.data;
});

export default request;
